import icon from "data-base64:~assets/icon_white.png"
import React, { useEffect, useState } from "react"
import { ThemeProvider } from "src/theme"

import { useStorage } from "@plasmohq/storage/hook"

import "~assets/css/popup.css"

import { Button } from "antd"

import DingtalkQrLoginFrame from "./DingtalkQrLoginFrame"
import MainContent from "./MainContent"
import PasswordLogin from "./PasswordLogin"

function IndexPopup() {
  const [isLogin] = useStorage("isLogin")
  const [loginErr, setLoginErr] = useStorage<string | undefined>("loginErr")
  // 是否为扫码登录
  const [isQrLogin, setIsQrLogin] = useState(true)
  // 登录类型文字
  const [loginTypeTxt, setLoginTypeTxt] = useState("切换[密码]登录")
  // 扫码登录组件key qrKey
  const [qrKey, setQrKey] = useState(0)

  const showLoginErr = () => {
    // 当loginErr不为空字符串或undefined时, 返回<div>loginErr</div>
    if (loginErr && loginErr.length > 0) {
      return <div>{loginErr}</div>
    } else {
      return null
    }
  }

  // 监控错误信息变化
  useEffect(() => {
    // 当loginErr不为空字符串或undefined时, 重置qrKey
    if (loginErr && loginErr.length > 0) {
      setQrKey((prev) => prev + 1)
    }
    // 5秒后清空loginErr
    setTimeout(() => {
      setLoginErr("").then()
    }, 5000)
  }, [loginErr])

  // 监控登录类型状态变化
  useEffect(() => {
    if (isQrLogin) {
      setLoginTypeTxt("切换[密码]登录")
    } else {
      setLoginTypeTxt("切换[扫码]登录")
    }
    setLoginErr("").then()
  }, [isQrLogin])

  return (
    <ThemeProvider>
      <div className="popup-wrap">
        {/*顶部栏*/}
        <div className="popup-header">
          {/*logo图片*/}
          <div className="popup-logo">
            <img src={icon} alt="logo" />
          </div>
          {/*标题*/}
          <div className="popup-title">
            <span>-大G浏览器助手-</span>
          </div>
        </div>
        {/*内容*/}
        <div className="popup-content">
          {!isLogin && (
            <div>
              <div className="login-switch-wrap">
                <Button type="link" onClick={() => setIsQrLogin(!isQrLogin)}>
                  {loginTypeTxt}
                </Button>
              </div>
              {isQrLogin ? (
                <DingtalkQrLoginFrame key={qrKey} />
              ) : (
                <PasswordLogin />
              )}
            </div>
          )}
          {isLogin && <MainContent />}
          <div className="login-error">{showLoginErr()}</div>
        </div>
      </div>
    </ThemeProvider>
  )
}

export default IndexPopup
